<template>
  <div>
    <h1>13-vue3如何实现响应式</h1>
  </div>
</template>

<script setup lang="ts">
function reactive(target = {}) {
  if (typeof target !== 'object' || target == null) {
    return target
  }

  // 代理配置
  const proxyConf = {
    get(target, key, receiver) {
      // 只处理本身属性
      const ownKeys = Reflect.ownKeys(target)
      if (ownKeys.includes(key)) {
        console.log('get', key)
      }
      const result = Reflect.get(target, key, receiver)
      return reactive(result)
    },
    set(target, key, val, receiver) {
      // 重复的数据，不处理
      if (val === target[key]) {
        return true
      }
      const ownKeys = Reflect.ownKeys(target)
      if (ownKeys.includes(key)) {
        console.log('已有的key', key)
      } else {
        console.log('新增的key', key)
      }
      const result = Reflect.set(target, key, val, receiver)
      return result
    },
    deleteProperty(target, key) {
      const result = Reflect.deleteProperty(target, key)
      return result
    }
  }

  // 生成代理对象
  const observed = new Proxy(target, proxyConf)
  return observed
}

const data = {
  name: 'zhangsan',
  age: 20,
  info: {
    city: 'beijing'
  }
}

const ref = reactive(data)

// ref.info.city
ref.age = 35
ref.age2 =34
</script>

<style scoped></style>
